import axios from "axios";
import { Loading, Message, MessageBox } from "ccui";
import store from "../store";
import { addUrlPerFix } from "@/basa/utils";

const baseURL = addUrlPerFix(process.env.VUE_APP_BASE_URL);
import Cookies from "js-cookie";
import Vue from "vue";
import { getArgs } from "@/basa/utils";
import { isShowErrorMessage } from "ccui/lib/utils/util";
axios.defaults.withCredentials = true;

const service = axios.create({
  baseURL: baseURL, // api 的 base_url
  timeout: 1000 * 60 // request timeout
});

let loadingObj;
let pageLoading = "";
let requestConfig;

// 请求拦截器
service.interceptors.request.use(
  config => {
    requestConfig = config;
    config.headers.Authorization = Cookies.get("access_token") || "";
    config.headers.APP_TOKEN = localStorage.appToken || "";
    // 加数据变动loading
    if (typeof config.data === "object" && config.data.isShowLoading === true) {
      delete config.data.isShowLoading;
      store.commit(
        "SET_LOADINGMESSAGE",
        config.data.loadingMessage || "处理中,请稍等..."
      );
      delete config.data.loadingMessage;
      loadingObj = Loading.service({
        lock: true,
        text: store.getters.loadingMessage,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.2)",
        customClass: "ccui-custom-loading"
      });
    }
    // 加页面列表loading
    if (
      typeof config.data === "object" &&
      config.data.isShowPageLoading === true
    ) {
      pageLoading = config.url;
      store.dispatch("setPageLoadingEnable", true);
      store.dispatch("setPageLoading", true);
      delete config.data.isShowPageLoading;
    }

    // 获取agentId
    config.data.agentId = getArgs("a");

    if (store.state.user.userDetal) {
      const userInfo = store.state.user.userDetal;
      config.data.baseAppId = userInfo.appId;
    }
    return config;
  },
  error => {
    // Do something with request error
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 关闭数据变动loading
    if (loadingObj !== undefined) {
      loadingObj.close();
      loadingObj = undefined;
    }
    // 关闭页面列表loading
    if (
      store.state.app.pageLoading.pageLoadingStatus &&
      response.config.url === pageLoading
    ) {
      Vue.nextTick(() => {
        store.dispatch("setPageLoading", false);
      });
    }
    // 后端报错处理
    if (response.data.code !== "0") {
      if (typeof response.data === "string") {
        if (response.data.substring(0, 15) === "<!DOCTYPE html>") {
          window.location.href =
            addUrlPerFix(process.env.VUE_APP_LOGIN) +
            "?redirectUrl=" +
            encodeURIComponent(window.location.href);
        }
      } else {
        // 依据code码做错误处理
        return errorHandler(response);
      }
    } else {
      // 请求正常
      return response;
    }
  },
  error => {
    // 系统错误处理
    if (loadingObj) {
      loadingObj.close();
      loadingObj = undefined;
    }
    let message =
      error.code === "ECONNABORTED"
        ? `<i class="el-icon-warning"></i>网络请求超时`
        : `<i class="el-icon-warning"></i>系统错误，请<a class="ccui-message-box-custom-link">联系管理员</a>`;
    Message.closeAll();
    MessageBox.alert(message, "提示", {
      distinguishCancelAndClose: true,
      dangerouslyUseHTMLString: true,
      customClass: "ccui-message-box-custom"
    });

    return Promise.reject(error);
  }
);

// 错误码处理
function errorHandler(response) {
  switch (response.data.code) {
    case "111":
      window.location.href =
        addUrlPerFix(process.env.VUE_APP_LOGIN) +
        "?redirectUrl=" +
        encodeURIComponent(window.location.href);
      return;
    case "112":
      window.location.href =
        addUrlPerFix(process.env.VUE_APP_OAUTH_URL) +
        "?CLIENT_ID=" +
        getArgs("a") +
        "&CALLBACK_URL=" +
        encodeURIComponent(window.location.href);
      return;
    case "305":
    case "307":
      store.dispatch("setRouter305", {
        isShow: true,
        message: response.data.message
      });
      return response;
    case "309":
      return response;
    default:
      Message.closeAll();
      // 区分业务状态码处理和系统状态码处理
      if (isShowErrorMessage(response.data.code)) {
        // customErrorHandle为自定义错误码的处理,如需要自定义状态码处理,放开注释
        // customErrorHandle(response) &&
        // 自行处理错误
        if (JSON.parse(requestConfig.data).selfHandle) {
          return response;
        } else {
          Message({
            message: response.data.message,
            type: "error",
            showClose: true,
            ccuiCustom: true,
            duration: 1000 * 8
          });
        }
      } else {
        MessageBox.alert(
          `<i class="el-icon-warning"></i>系统错误（错误代码：${response.data.code}），请<a class="ccui-message-box-custom-link">联系管理员</a>`,
          "提示",
          {
            distinguishCancelAndClose: true,
            dangerouslyUseHTMLString: true,
            customClass: "ccui-message-box-custom"
          }
        );
      }
      return Promise.reject(response);
  }
}

/*
 * 自定义错误码的处理
 * 以下为示例
 * 如果需要之后的Message执行,需方法里返回return true
 * */
// function customErrorHandle(response) {
//   let obj = {
//     "10202": () => {
//       MessageBox.alert(
//         `<i class="el-icon-warning"></i>店铺已关闭</a>`,
//         "提示",
//         {
//           distinguishCancelAndClose: true,
//           dangerouslyUseHTMLString: true,
//           customClass: "ccui-message-box-custom",
//           callback: () => {
//             window.location.href =
//               process.env.VUE_APP_BASE_URL +
//               "goods/goodsdistribution/alllist?a=" +
//               window.getArgs("a");
//           }
//         }
//       );
//     },
//     "10301": () => {
//       MessageBox.alert(
//         `<i class="el-icon-warning"></i>${response.data.message}</a>`,
//         "提示",
//         {
//           distinguishCancelAndClose: true,
//           dangerouslyUseHTMLString: true,
//           customClass: "ccui-message-box-custom",
//           callback: () => {
//             window.location.href =
//               process.env.VUE_APP_BASE_URL +
//               "orders/enterprise-order?a=" +
//               window.getArgs("a");
//           }
//         }
//       );
//     }
//   };
//
//   return obj[response.data.code]();
// }

export default service;
